<?php
/**
 * ObsService.php
 * ==============================================
 * Copy right 2021  by tianmtech.cn
 * ----------------------------------------------
 * This is not a free software, without any authorization is not allowed to use and spread.
 * ==============================================
 *
 * @desc: 华为云obs上传服务
 * @author: zhouliang@tianmtech.cn
 * @version: v1.0.0
 * @since: 2022/1/5 16:10
 */
namespace App\Services\Tools;

use Obs\ObsClient;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\Storage;

class ObsService
{
    /**
     * 基础的文件上传方法(华为云OBS存储)
     *
     * @param  null  $file  要存储的文件对象
     * @param  array  $file_type  要上传的所有的文件类型(数组)
     */
    static function uploadFile($file, array $file_type = [])
    {
        if (empty($file)) {
            throw new BasicException(10050);
        }
        //判断文件是否有效
        if ($file->isValid()) {
            //原始名称
            $originalName = $file->getClientOriginalName();
            //扩展名称
            $ext = $file->getClientOriginalExtension();
            //文件类型
            $type = $file->getClientMimeType();
            //文件大小
            $fileSize = $file->getSize();

            if (!empty($file_type)) {
                if (!in_array($type, $file_type)) {
                    throw new BasicException(10051);
                }
            }
            $path = 'adm';
            $realPath = $file->getRealPath();
            $filename = md5(date('YmdHis', time()) . mt_rand(101, 999)) . str_random(5) . '.' . $ext;
            $target = $path . '/' . date('Y-m-d') . '/' . $filename;

            $disk = Storage::disk('local');
            $upload = $disk->put($target, file_get_contents($realPath));
            if (!$upload) {
                throw new BasicException(10053);
            }
            $resp = self::putObs($target, storage_path('app') . '/' . $target);
            if (!isset($resp['HttpStatusCode']) || $resp['HttpStatusCode'] != 200) {
                throw new BasicException(400005);
            }
            $data = [
                'file_name'  => $originalName,
                'extension'  => $ext,
                'size'       => $fileSize,
                'user_id'    => app('request')->admin_id,
                'ip'         => app('request')->getClientIp(),
                'url'        => $target,
                'is_deleted' => 0,
                'type'       => 14,
            ];
            app('model_file')->insert($data);

            return env('OBS_HOST') . '/' . $target;
        } else {
            throw new BasicException(10052);
        }
    }

    public static function putObs($target, $sourceFile)
    {
        $obsClient = new ObsClient([
            'key'      => env('OBS_AK'),
            'secret'   => env('OBS_SK'),
            'endpoint' => env('OBS_ENDPOINT'),
        ]);

        return $obsClient->putObject([
            'Bucket'     => env('OBS_BUCKET'),
            'Key'        => $target,
            'SourceFile' => $sourceFile,
        ]);
    }

    /**
     * Desc: 删除单个对象
     * User: XiaoSC
     * Date: 2022/1/19 20:45
     * ApiLink:
     *
     * @param $url 文件资源相对地址
     */
    public static function delFileObject($url)
    {
        $obsClient = new ObsClient([
            'key'      => env('OBS_AK'),
            'secret'   => env('OBS_SK'),
            'endpoint' => env('OBS_ENDPOINT'),
        ]);

        $resp = $obsClient->deleteObject([
            'Bucket' => env('OBS_BUCKET'),
            'Key'    => $url,
        ]);
    }
}
